package com.entrogy.timing;

import com.entrogy.utils.THDio;


import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;

public class SetDeviceTimeThread extends Thread{

	private Logger logger = LoggerFactory.getLogger(SetDeviceTimeThread.class);

	private String deviceId;
	//每个学校对应的设备管理系统后台的url
	private String pathUrl;
	private String key;
	private HashMap<Integer, String> errMsg;

	public SetDeviceTimeThread(String deviceId, String pathUrl, String key) throws SQLException {
		this.key = key;
		this.pathUrl = pathUrl;
		this.deviceId = deviceId;
		this.errMsg = new HashMap<>();
		this.errMsg.put(105, "设备不存在");
		this.errMsg.put(111, "设备不在线");
		this.errMsg.put(112, "链接设备超时");
		this.errMsg.put(113, "链接设备出错");
		this.errMsg.put(500, "服务器繁忙");
	}

	@Override
	public void run() {
		int count = 0;
		JSONObject params = new JSONObject();
		int threshTimes = 50;
		int sleepTime = 1000 * 60 * 5;
		params.put("device_id", deviceId);
		THDio thd = new THDio();
		while (true) {
			long time = new Date().getTime() / 1000;
			params.put("set_time", time);
			JSONObject res = thd.THD_interface(pathUrl, "/device/set_device_time", params, false, key);
			if (0 != res.getInt("code") && count <= threshTimes) {
				switch (res.getInt("code")) {
					case 111:
					case 112:
					case 113:
					case 500:
						logger.info("设备" + deviceId + "第" + count + "次" + "设置权限失败，原因：" + res.toString());
						count++;
						break;
					case 105:
						logger.info("设备" + deviceId + "第" + count + "次" + "设置权限失败，原因：" + res.getString("data"));
						count = threshTimes * 2;//105就退出
						break;
					default:
				}
			} else {
				logger.info("设备" + deviceId + "第" + count + "次" + "设置权限成功");
				break;
			}

			try {
				Thread.sleep(sleepTime);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}
